import React, { Component } from 'react';
import styled from 'styled-components/native';
import { Keyboard } from 'react-native';
import Touchable from '@appandflow/touchable';
import { graphql, compose } from 'react-apollo';
import { connect } from 'react-redux';
import { EvilIcons } from '@expo/vector-icons';

import { colors, dimens, strings } from '../utils/constants';
import { goBack } from '../actions/nav';
import GET_TWEETS_QUERY from '../graphql/queries/getTweets';
import CREATE_TWEET_MUTATION from '../graphql/mutations/createTweet';

import HeaderAvatar from '../components/HeaderAvatar';
import { ToolbarButton } from '../components/common';
import Loading from '../components/Loading';

const MAX_TEXT_LENGTH = 140;

const Root = styled.View`
  width: 100%;
  height: 100%;
  flex: 1;
  background-color: ${colors.WHITE};
  position: relative;
  padding: ${dimens.PADDING};
`;

const WeiboInput = styled.TextInput.attrs({
  multiline: true,
  placeholder: `What's happening now...`,
  autoFocus: true,
  maxLength: MAX_TEXT_LENGTH,
  selectionColor: colors.PRIMARY,
  underlineColorAndroid: 'transparent'
})`
  width: 100%;
  height: 20%;
  font-size: 18;
  color: ${colors.PRIMARY_TEXT};
  textAlignVertical: top;
`;

const TextLength = styled.Text`
  font-size: 18;
  color: ${colors.PRIMARY};
  position: absolute;
  right: 16;
  top: 25%;
`;

const SubmitButton = styled(Touchable).attrs({
  feedback: 'opacity'
})`
  width: 80;
  height: 40;
  background-color: ${colors.PRIMARY};
  align-items: center;
  justify-content: center;
  border-radius: 20;
  position: absolute;
  right: ${dimens.PADDING};
  top: 30%;
`;

const SubmitButtonText = styled.Text`
  font-size: 18;
  color: ${colors.WHITE};
`;

class NewTweetScreen extends Component {

  static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    const headerLeft = <HeaderAvatar />;
    const headerRight = (
      <ToolbarButton onPressed={params.goBack ? () => params.goBack() : () => null}>
        <EvilIcons size={30} color={colors.PRIMARY} name="close" />
      </ToolbarButton>
    );
    const title = params.title || strings.SEND_WEIBO_TITLE;
    return {headerLeft, headerRight, title};
  }

  state = {
    text: '',
    isProcessing: false
  }

  componentDidMount() {
    this.props.navigation.setParams({
      goBack: this._goBack
    });
  }

  get _textLength() {
    return MAX_TEXT_LENGTH - this.state.text.length;
  }

  get _isSubmitDisabled() {
    return this.state.text.length < 5 || this.state.isProcessing;
  }

  _goBack = () => {
    Keyboard.dismiss();
    this.props.goBack();
  }

  _onChangeText = text => this.setState({ text });

  _setNavigationParams = params => this.props.navigation.setParams(params);

  _onSubmitButtonPressed = async () => {
    this._setNavigationParams({ title: strings.SENDING });
    this.setState({ isProcessing: true });
    const { user } = this.props;
    await this.props.mutate({
      variables: {
        text: this.state.text
      },
      optimisticResponse: {
        __typename: 'Mutation',
        createTweet: {
          __typename: 'Tweet',
          text: this.state.text,
          favouriteCount: 0,
          isFavourite: false,
          _id: Math.round(Math.random() * -1000000),
          createdAt: new Date(),
          user: {
            __typename: 'User',
            username: user.username,
            firstName: user.firstName,
            lastName: user.lastName,
            avatar: user.avatar
          }
        }
      },
      update: (store, { data: { createTweet } }) => {
        const data = store.readQuery({ query: GET_TWEETS_QUERY });
        if (!data.getTweets.find(item => item._id === createTweet._id)) {
          store.writeQuery({ query: GET_TWEETS_QUERY, data: { getTweets: [{ ...createTweet }, ...data.getTweets]}});
        }
      }
    });

    this._setNavigationParams({ title: strings.SEND_WEIBO_TITLE });
    this.setState({ isProcessing: false });
    Keyboard.dismiss();
    this.props.goBack();
  }

  render() {
    return (
      <Root>
        <WeiboInput value={this.state.text} onChangeText={this._onChangeText} />
        <TextLength>{this._textLength}</TextLength>
        <SubmitButton onPress={this._onSubmitButtonPressed} disabled={this._isSubmitDisabled}>
          {
            this.state.isProcessing ?
            <Loading size="small" color={colors.WHITE} /> :
            <SubmitButtonText>Tweet</SubmitButtonText>
          }
        </SubmitButton>
      </Root>
    );
  }
}

const mapStateToProps = (state) => ({
    user: state.user.info
  })

export default compose(
  graphql(CREATE_TWEET_MUTATION),
  connect(mapStateToProps, { goBack })
)(NewTweetScreen);
